<template>
	<el-dialog 
		:title="dialog.title[dialog.action]" 
		v-model="dialog.visible" 
		v-model:loading="dialog.loading"
		:fullHeight="dialog.fullHeight"
		:width="700"
		@closed="closed"
	>
		<el-form ref="form" label-width="80px">
			<el-form-item label="角色名称">{{role.name}}</el-form-item>
			<el-form-item label="状态">
				<el-tag size="mini" :type="role.status.value == 1 ? 'success' : 'danger'">{{role.status.name}}</el-tag>
			</el-form-item>
			<el-form-item label="权限">
				<permission v-model="role.permission" :preview="true"></permission>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="dialog.visible=false" >关闭</el-button>
		</template>
	</el-dialog>
</template>

<script>
    import { defineAsyncComponent } from 'vue'
    const permission = defineAsyncComponent(() => import('./permission'))
	export default {
		emits: ['success', 'closed'],
        components: {
			permission,
		},
		data() {
			return {
				/**
				 * 弹框页面数据
				 */
				dialog: {
					action: 'detail',
					title: {
						detail: '角色详情'
					},
					visible: false,
					loading: '',
					height: '',
					fullHeight: true
				},

				/**
				 * 角色数据
				 */
                role: {
					status: {
						value: 0,
						name: ''
					}
				},
			}
		},
		methods: {
			/**
			 * 初始化页面
			 */
			open(id){
				this.dialog.visible = true
				this.$nextTick(() => {
					this.dialog.loading = 'start'
					this.setData(id).then(res => {
						this.dialog.loading = 'end'
					}).catch(() => {
						this.dialog.loading = 'wait'
					})
					return this;
				})
			},

			/**
			 * 设置数据
			 */
			setData(id) {
				return new Promise((resolve, reject) => {
					this.$API.system.role.action.get({id: id}).then(res => {
						res.data.permission = this.permissionsHander(res.data.permission)
						this.role = res.data
						resolve(res.data)
					}).catch(error => {
						reject(error)
					})
				})
			},

			/**
			 * 组装权限
			 */
			permissionsHander(_permissions) {
				let data = [];
				_permissions.forEach(ele => {
				if (ele.checked || ele.indeterminate) {
					if (ele.children) {
						let _children = this.permissionsHander(ele.children)
						if ( ! _children) {
							delete ele['children']
						} else {
							ele.children = _children
						}
					}

					if (ele.permission) {
						let _permissions = this.permissionsHander(ele.permission)
						if ( ! _permissions) {
							delete ele['permissions']
						} else {
							ele.permissions = _permissions
						}
					}

					data.push(ele)
				}
				});
				return data
			},
		}
	}
</script>

<style>
</style>
